import logging
import jwt
from datetime import datetime, timedelta
from typing import Optional, Dict, Any

logger = logging.getLogger(__name__)
# JWT配置
SECRET_KEY = "your-secret-key-change-in-production"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60  * 24 * 30

class JWTUtils:
    @staticmethod
    def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
        """
        创建访问令牌
        
        Args:
            data: 要编码的数据
            expires_delta: 过期时间增量
            
        Returns:
            str: JWT令牌
        """
        to_encode = data.copy()
        if expires_delta:
            expire = datetime.now(datetime.timezone.utc) + expires_delta
        else:
            expire = datetime.now(datetime.timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        
        to_encode.update({"exp": expire})
        encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
        return encoded_jwt
    
    @staticmethod
    def decode_access_token(token: str) -> Dict[str, Any]:
        """
        解码访问令牌
        
        Args:
            token: JWT令牌
            
        Returns:
            Dict[str, Any]: 解码后的数据
            
        Raises:
            jwt.PyJWTError: 当令牌无效或过期时
        """
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    
    @staticmethod
    def verify_token(token: str) -> Optional[int]:
        """
        验证令牌并返回用户ID
        
        Args:
            token: JWT令牌
            
        Returns:
            Optional[int]: 用户ID，如果令牌无效则返回None
        """
        try:
            payload = JWTUtils.decode_access_token(token)
            user_id: int = payload.get("sub")
            if user_id is None:
                return None
            return int(user_id)
        except jwt.PyJWTError as e:
            logger.error(f"JWT验证失败: {e}")
            return None